<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽" />
    <el-button round v-if='updateNodes.length > 0' @click="batchSave">批量保存</el-button>
    <el-button round @click="batchDel" type="danger">批量删除</el-button>
    <!-- accordion 手风琴 draggable 拖拽 allow-drop 拖拽时判定目标节点能否被放置-->
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
      :default-expanded-keys="expandedKey" :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop"
      ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if='node.level <= 2' type="text" size="mini" @click="() => append(data)">Append</el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">Edit</el-button>
          <el-button v-if='node.isLeaf' type="text" size="mini" @click="() => remove(node, data)">Delete</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <span>
        <el-form :model="category">
          <el-form-item label="分类">
            <el-input v-model="category.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图标">
            <el-input v-model="category.icon" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="计量单位">
            <el-input v-model="category.productUnit" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      // //被选中的元素
      // getCheckedNodes: [],
      //父节点
      pCid: [],
      //是否开启拖拽
      draggable: false,
      //更新最新的分类顺序
      updateNodes: [],
      //子节点最大深度
      maxLevel: 0,
      //对话框主题
      title: '', //edit、add
      //对话框类型
      dialogType: '',
      //默认展开的节点
      expandedKey: [],
      category: {
        name: '',
        catLevel: '',
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: '',
        productUnit: '',
        parentCid: ''
      },
      //默认不显示对话框
      dialogVisible: false,
      menus: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getMenuList() {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => { //{data} 解构
        console.log('成功获取菜单数据：', data.data)
        this.menus = data.data
      })
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单顺序等修改成功',
          type: 'success',
        })
        //刷新新的菜单
        this.getMenuList();
        //展开菜单
        this.expandedKey = this.pCid
        this.updateNodes = []
        this.maxLevel = 0
      });
    },
    batchDel() {
      console.log("batchDel")
      var catIds = []
      var catNames = []
      console.log(this.$refs.menuTree.getCheckedNodes())
      var checkNodes = this.$refs.menuTree.getCheckedNodes()
      console.log("被选中的元素：", checkNodes)
      checkNodes.forEach(e => {
        catIds.push(e.catId)
        catNames.push(e.name)
      });
      this.$confirm(`是否批量删除【${catIds}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.$message({
              message: '批量删除菜单成功',
              type: 'success'
            })
            this.getMenuList()
            this.expandedKey = this.pCid
          });
        })
        .catch(() => {
          this.$message({
            message: '批量删除失败',
            type: 'fail'
          })
          console.log("批量删除失败")
        })

    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('handleDrop: ', draggingNode, dropNode, dropType);
      //1.当前节点最新的父节点id,从兄弟node里面找
      let pCid = 0
      let siblings = null
      if (dropType == 'inner') {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      } else {
        //dropNode 为一层分类，没有父节点，默认为0
        pCid = dropNode.parent.data.catId || 0
        siblings = dropNode.parent.childNodes
      }
      this.pCid.push(pCid)

      //2.当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //当前节点层级变化
            catLevel = siblings[i].level
            //修改他子节点的层级
            this.updateChildNodeLevel(siblings[i])
          }
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i, parentCid: pCid })
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i })
        }
      }
      //3.当前拖拽节点的最新层级
      console.log("更新数据：", this.updateNodes)

    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        //遍历子节点元素
        node.childNodes.forEach(e => {
          this.updateNodes.push({ catId: e.data.catId, catLevel: e.level })
          this.updateChildNodeLevel(e)
        });
      }
    },
    //最大三级菜单
    allowDrop(draggingNode, dropNode, type) {
      console.log('allowDrop：', draggingNode, dropNode, type)
      // 步骤1 计算出当前拖动的节点（draggingNode）的总层数
      //1.被拖动的当前节点以及所在父节点总层数 <=3
      var currentNodeMaxLevel = this.countNodeLevel(draggingNode);
      //2.当前正在拖动的节点+父节点所在的深度不大于3即可
      let currentNodeDeep = Math.abs(currentNodeMaxLevel - draggingNode.level + 1)
      console.log('深度：', currentNodeDeep)
      // this.maxLevel
      if (type == 'inner') {
        return (currentNodeDeep + dropNode.level) <= 3
      } else {
        return (currentNodeDeep + dropNode.parent.level) <= 3
      }
    },
    //当前拖动节点子节点的最大层级
    countNodeLevel(node) {
      if (!node.isLeaf) {
        node.childNodes.forEach(childNode => {
          let { level } = childNode
          this.maxLevel = level > this.maxLevel ? level : this.maxLevel;
          this.countNodeLevel(childNode)
        });
      }
      return this.maxLevel;
    },
    append(data) {
      this.dialogType = 'add'
      this.title = '添加分类'
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      //新增的时候数据需要清空
      this.category.catId = null;
      this.category.name = '';
      this.category.icon = '';
      this.category.productUnit = '';
      this.category.sort = 0;
      this.category.showStatus = 1;
    },
    edit(data) {
      console.log("需要修改的数据: ", data)
      this.dialogType = 'edit'
      this.title = '修改分类'
      this.dialogVisible = true
      //1.弹出对话框
      //2.获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        console.log('要回显的数据', data)
        let { name, catId, icon, productUnit, parentCid } = data.data
        this.category.name = name
        this.category.catId = catId
        this.category.icon = icon
        this.category.productUnit = productUnit
        this.category.parentCid = parentCid
      })
    },
    submitData() {
      if (this.dialogType === 'add') {
        this.addCategory()
      } else {
        this.editCategory();
      }
      //关闭对话框
      this.dialogVisible = false;
      //刷新新的菜单
      this.getMenuList();
      //展开菜单
      this.expandedKey = [this.category.parentCid]
    },
    // 添加分类
    addCategory() {
      console.log('添加分类数据: ', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: '保存操作成功',
          type: 'success',
        })
      });
    },
    // 编辑分类
    editCategory() {
      //解构
      var { name, catId, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({ name, catId, icon, productUnit }, false),
      }).then(({ data }) => {
        this.$message({
          message: '修改操作成功',
          type: 'success',
        })

      });
    },
    remove(node, data) {
      console.log(node)
      var ids = [data.catId]
      // 使用飘号``才能使用插值表达式 ${data.name}
      this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: '菜单删除操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              //刷新新的菜单
              this.getMenuList();
              a
              //展开菜单
              this.expandedKey = [node.parent.data.catId]
            }
          })
        });
      })
    },
    cancel() {
      this.dialogVisible = false
    },

  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenuList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, //生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
    this.getMenuList();
  }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
/* @import url(); 引入公共css类 */
</style>
